Springboot

您所在的位置:网站首页 springboot 错误页面 Springboot

Springboot

2024-07-03 11:38| 来源: 网络整理| 查看: 265

此方法适用于项目打jar包的方式!!!

 

1、在config包下创建ErrorConfiguration类:

import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.ErrorPageRegistrar; import org.springframework.boot.web.server.ErrorPageRegistry; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; /** *

自定义错误页面(4xx/5xx)处理类

* @Description 自定义错误页面(4xx/5xx)处理类 * @author MengMeng * Created date: 2018/10/11 * @Since JDK 1.80_171 */ @Component public class ErrorConfiguration implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { ErrorPage[] errorPages = new ErrorPage[]{ new ErrorPage(HttpStatus.FORBIDDEN, "/error/403"), new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"), new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"), new ErrorPage(Throwable.class, "/error/500") }; registry.addErrorPages(errorPages); } }

 

2、在controller包下创建ErrorController:

import org.apache.catalina.servlet4preview.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; @Controller public class ErrorController { /** *

自定义错误处理的Controller类

* @Description 自定义错误处理的Controller类 * @author MengMeng *

Created date: 2018/10/11

* @version: 0.1 * @since JDK 1.80_144 */ @RequestMapping(value = "/error/{code}") public String error(@PathVariable int code, Model model) { String pager = ""; switch (code) { case 403: model.addAttribute("code", 403); pager = "error/page"; break; case 404: model.addAttribute("code", 404); pager = "error/page"; break; case 500: model.addAttribute("code", 500); pager = "error/page"; break; } return pager; } }

 

3、创建错误页面,HTML代码:

网站访问失败 你所访问的页面不存在! 可能的原因: 1.内容填写有错误。 2.链接过了保质期。 3.所在页面时间过长。 4.如果还未解决,请向管理员反馈! 回到网站首页;

 

效果图:

 

 

相关学习链接:

https://blog.csdn.net/hp_yangpeng/article/details/81004227

https://blog.csdn.net/fantomelarmes/article/details/81061435#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%BC%82%E5%B8%B8%E9%A1%B5%E9%9D%A24xx5xx

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3